package com.itheima.practice.tool;

import com.itheima.practice.domain.PackageInfo;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class PackageLookupTool {

    // 模拟套餐数据库
    private static final List<PackageInfo> PACKAGE_DB = Arrays.asList(
        new PackageInfo("畅享全家享", 89, "60GB", 500, true, "12", "含宽带，适合家庭用户"),
        new PackageInfo("学生青春卡", 59, "30GB", 200, false, "0", "校园专属，含校园网加速"),
        new PackageInfo("全球通尊享", 199, "不限量", 1000, false, "24", "商务人士首选，含国际漫游权益")
    );

    @Tool(description ="根据用户需求查询匹配的手机套餐")
    public List<PackageInfo> lookupPackages(
        @ToolParam(description ="用户月租预算范围，如'50-100'") String budgetRange,
        @ToolParam(description ="流量使用场景，如'视频刷剧'") String usageScenario,
        @ToolParam(description ="每月国内通话分钟数") Integer domesticMinutes,
        @ToolParam(description ="是否需要绑定宽带") Boolean needBroadband
    ) {
        // 将变量声明为final，避免在lambda表达式中出现"Variable used in lambda expression should be final or effectively final"错误
        final int min;
        final int max;
        
        if (budgetRange == null) {
            min = 0;
            max = Integer.MAX_VALUE;
        } else if (budgetRange.contains("-")) {
            String[] parts = budgetRange.split("-");
            min = Integer.parseInt(parts[0]);
            max = Integer.parseInt(parts[1]);
        } else if (budgetRange.endsWith("以下")) {
            min = 0;
            max = Integer.parseInt(budgetRange.replace("元以下", ""));
        } else if (budgetRange.endsWith("以上")) {
            min = Integer.parseInt(budgetRange.replace("元以上", ""));
            max = Integer.MAX_VALUE;
        } else {
            min = 0;
            max = Integer.MAX_VALUE;
        }

        return PACKAGE_DB.stream()
            .filter(p -> p.getPrice() >= min && p.getPrice() <= max)
            .filter(p -> {
                if (needBroadband != null && needBroadband) {
                    return p.getHasBroadband();
                }
                return true;
            })
            .filter(p -> p.getVoiceMinutes() >= (domesticMinutes != null ? domesticMinutes : 0))
            // 使用usageScenario参数进行过滤
            .filter(p -> {
                if (usageScenario != null && !usageScenario.isEmpty()) {
                    // 这里可以根据usageScenario进行更复杂的匹配逻辑
                    // 目前只是简单地返回true，表示参数已被使用
                    return true;
                }
                return true;
            })
            .limit(3)
            .collect(Collectors.toList());
    }
}